package com.gxar.uaa.server.base.dubbo;

import com.gxar.uaa.api.client.IUserClient;
import com.gxar.uaa.api.dto.menu.SysMenu;
import com.gxar.uaa.api.dto.role.SysRole;
import com.gxar.uaa.server.db.service.MenuService;
import com.gxar.uaa.server.db.service.RoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/1/24 14:37
 */
@Slf4j
@DubboService(version = "1.0.0")
@RequiredArgsConstructor
public class IUserClientImpl implements IUserClient {

    private final RoleService roleService;
    private final MenuService menuService;

    @Override
    public List<SysMenu> findMenuByUserId(String app, Long userId, Integer type) {
        try {
            List<SysRole> roleList = roleService.findRolesByUserId(app, userId);
            Set<String> roleCodes = Optional.ofNullable(roleList).orElse(Collections.emptyList()).stream().map(SysRole::getCode).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(roleList)) {
                return menuService.findByRoleCodes(app, roleCodes, type);
            }
            return null;
        } catch (RuntimeException e) {
            log.info("查询用户菜单异常: {}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

}
